using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using PhillyCodeCamp.UI;

namespace PhillyCodeCamp.Web
{
    public abstract class ViewBase : Page, IView
    {
        private const string ScriptTagBegin = "<script type='text/javascript'>";
        private const string ScriptTagEnd = "</script>";

        public void ShowErrors(IList<string> messages)
        {
            var builder = new StringBuilder();
            foreach (string message in messages)
            {
                builder.Append(message + "\\r");
            }


            ShowAlert(builder.ToString());

        }

        public void ShowError(string message)
        {
            ShowAlert(message);
        }

        private void ShowAlert(string message)
        {
            RegisterScript("alert", string.Format("alert('{0}');", message.Replace("'", "\'")));
        }

        protected void RegisterScript(string key, string script)
        {
            if (!script.ToUpper().StartsWith("<SCRIPT"))
            {
                script = ScriptTagBegin + script + ScriptTagEnd;
            }
            if (!ClientScript.IsClientScriptBlockRegistered(key))
            {
                ClientScript.RegisterStartupScript(GetType(), key, script, false);
            }
        }

        protected void UnRegisterScript(string key)
        {
            if (!ClientScript.IsClientScriptBlockRegistered(key))
            {
                ClientScript.RegisterStartupScript(GetType(), key, string.Empty, false);
            }
        }

    }
}